package com.thh.common.utils;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;

/**
 * @Desc aes工具
 * <p>encrypt加密</p>
 * <p>decrypt解密</p>
 * @Author tanhh
 * @Date 2022/6/26 9:08
 * @Version 1.0
 **/
public class AESUtils {

    public static void main(String[] args) {
        String data = "123456";
        String key = generateKey();
        System.out.println("key = " + key);
        String encrypt = encrypt(data, key);
        System.out.println("encrypt = " + encrypt);
        String decrypt = decrypt(encrypt, key);
        System.out.println("decrypt = " + decrypt);
    }

    /*
     * @Author tanhuihuang
     * @Description 自动生成秘钥，转成16进制来表示
     * @Date 9:48 2022/6/26
     * @return java.lang.String
     **/
    public static String generateKey() {
        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        return  HexUtil.encodeHexStr(key);
    }


    /**
     * 解密
     * @param encryptData 要解密的String
     * @param keyStr 秘钥
     * @return 解密后的 字符串
     */
    public static String decrypt(String encryptData, String keyStr) {
        byte[] key = HexUtil.decodeHex(keyStr);
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        //解密为16进制表示
        return aes.decryptStr(encryptData);
    }


    /**
     * 加密
     *
     * @param data 要加密的String
     * @param keyStr 秘钥
     * @return 加密后的 字符串
     */
    public static String encrypt(String data, String keyStr) {
        byte[] key = HexUtil.decodeHex(keyStr);
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        //加密为16进制表示
        return aes.encryptHex(data);
    }
}
